﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Checkpoint2XNA.Models.Chess
{
    public class Bishop : Model3D
    {
        const float BASE_RADIUS = .3f;
        const float BASE_HEIGHT = .4f;
        const float SPHERE_RADIUS = .2f;

        public Cylinder Base;
        public SolidSphere Sphere;

        public Bishop(Vector3 p, float size, ChessSide s): base(p, s)
        {
            Base = new Cylinder(p, size * BASE_RADIUS, size * BASE_HEIGHT, Color);
            Sphere = new SolidSphere(new Vector3(p.X, p.Y + size * SPHERE_RADIUS + size * BASE_HEIGHT, p.Z), size * SPHERE_RADIUS, Color);
        }

        public override void MoveTo(Vector3 point)
        {
            var yOffset = Sphere.Position.Y - Base.Bottom.Y;
            Base.MoveTo(point);
            Sphere.MoveTo(new Vector3(point.X, point.Y + yOffset, point.Z));
            CenterBottom = point;
        }

        public override Microsoft.Xna.Framework.Color GetColorAt(Microsoft.Xna.Framework.Vector3 point)
        {
            return Color;
        }

        public override Microsoft.Xna.Framework.Vector3 GetNormal(Microsoft.Xna.Framework.Vector3 point)
        {

            if (Vector3.Distance(point, Sphere.Position) <= Sphere.Radius + 1E-2)
                return Sphere.GetNormal(point);
            else
                return Base.GetNormal(point);
        }

        public override double RayCollide(Microsoft.Xna.Framework.Vector3 origin, Microsoft.Xna.Framework.Vector3 normalVector)
        {
            var t = Double.MaxValue;
            double temp;
            if ((temp = Base.RayCollide(origin, normalVector)) > 0 && temp < t)
                t = temp;

            if ((temp = Sphere.RayCollide(origin, normalVector)) > 0 && temp < t)
                t = temp;

            return t == Double.MaxValue ? -1 : t;
        }
    }
}
